package com.meida.module.system.provider.service.impl;

import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.DateUtils;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.system.client.entity.SysUserKeyword;
import com.meida.module.system.provider.mapper.SysUserKeywordMapper;
import com.meida.module.system.provider.service.SysUserKeywordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 关键词接口实现类
 *
 * @author flyme
 * @date 2020-05-20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysUserKeywordServiceImpl extends BaseServiceImpl<SysUserKeywordMapper, SysUserKeyword> implements SysUserKeywordService {

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, SysUserKeyword suk, EntityMap extra) {
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<SysUserKeyword> cq, SysUserKeyword suk, EntityMap requestMap) {
        cq.select("count(content) searchCount", "count(DISTINCT userId) searchUserCount");
        cq.groupBy("content");
        cq.orderByDesc("searchCount");
        return ResultBody.ok();
    }

    @Override
    public void afterPageList(CriteriaQuery<SysUserKeyword> cq, List<EntityMap> data, ResultBody resultBody) {

        EntityMap result = totalSearch();
        resultBody.setExtra(result);
        super.afterPageList(cq, data, resultBody);
    }

    private EntityMap totalSearch() {
        EntityMap result = new EntityMap();
        CriteriaQuery cq = new CriteriaQuery(SysUserKeyword.class);
        cq.select("count(content) searchCount", "count(DISTINCT userId) searchUserCount", "DATE_FORMAT( createTime, '%Y-%m-%d' ) AS time", "ROUND(count( content )/count( DISTINCT userId ),2) avgCount");
        EntityMap totalMap = findOne(cq);
        String begin = DateUtils.getFirstDayOfMonth().toString();
        cq.ge("createTime", begin);
        cq.le("createTime", DateUtils.getLastDayOfMonth().toString());
        cq.groupBy("time");
        List<EntityMap> list = selectEntityMap(cq);
        if (FlymeUtils.isNotEmpty(list)) {
            //搜搜用户数
            List<Map<String, Object>> userCountList = new ArrayList<>();
            //平均数
            List<Map<String, Object>> avgCountList = new ArrayList<>();
            int num = DateUtils.getMonthDaysNum();
            for (int i = 0; i < num; i++) {
                String date = DateUtils.plusDays(DateUtils.getFirstDayOfMonth(), i);
                Map<String, Object> userCountMap = new HashMap<>();
                Map<String, Object> avgCountMap = new HashMap<>();
                userCountMap.put("x", date);
                avgCountMap.put("x", date);
                userCountMap.put("y", 0);
                avgCountMap.put("y", 0);
                for (Map<String, Object> map : list) {
                    String totalAmount = map.get("searchUserCount").toString();
                    String orderCount = map.get("searchUserCount").toString();
                    String d = map.get("time").toString();
                    if (d.equals(date)) {
                        userCountMap.put("y", new BigDecimal(totalAmount));
                        avgCountMap.put("y", Integer.parseInt(orderCount));
                    }
                }
                userCountList.add(userCountMap);
                avgCountList.add(avgCountMap);
            }
            Integer searchCount = totalMap.getInt("searchCount", 0);
            BigDecimal avgCount = totalMap.getBigDecimal("avgCount");
            result.put("userCountList", userCountList);
            result.put("avgCountList", avgCountList);
            result.put("searchCount", searchCount);
            result.put("avgCount", avgCount);
        }
        return result;
    }

    @Override
    public ResultBody insert(String keyWord) {
        Long userId = OpenHelper.getUserId();
        SysUserKeyword userKeyword = new SysUserKeyword();
        userKeyword.setUserId(userId);
        userKeyword.setContent(keyWord);
        save(userKeyword);
        return ResultBody.ok();
    }


}
